/**
 * ReportGear(2011)
 */
package com.reportgear.designer.editor.object;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;

/**
 * 文本编辑器
 * 
 * @version 1.0 2011-4-26
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class TextEditor extends Editor {
	/**
	 * UID
	 */
	private static final long serialVersionUID = -3895426811557350340L;
	private JTextField textField;
	private String oldValue;

	public TextEditor() {
		this(null);
	}

	public TextEditor(String name) {
		this(null, name);
	}

	public TextEditor(Object value) {
		this(value, "");
	}

	public TextEditor(Object value, String name) {
		this.oldValue = "";
		this.setLayout(new BorderLayout());
		this.textField = new JTextField();
		this.add(this.textField, BorderLayout.CENTER);

		this.textField.addKeyListener(new KeyListener() {
			public void keyTyped(KeyEvent event) {
			}

			public void keyPressed(KeyEvent event) {
			}

			public void keyReleased(KeyEvent event) {
				int keyCode = event.getKeyCode();
				if (keyCode == KeyEvent.VK_ESCAPE) {
					TextEditor.this.textField.setText(TextEditor.this.oldValue);
				} else {
					if (keyCode != KeyEvent.VK_ENTER) {
						return;
					}

					fireEditingStopped();
				}
			}
		});

		this.setValue(value);
		this.setName(name);
	}

	public int getHorizontalAlignment() {
		return this.textField.getHorizontalAlignment();
	}

	public void setHorizontalAlignment(int alignment) {
		this.textField.setHorizontalAlignment(alignment);
	}

	public Object getValue() {
		return this.textField.getText();
	}

	public void setValue(Object value) {
		if (value == null) {
			value = "";
		}
		this.oldValue = value.toString();
		this.textField.setText(this.oldValue);
	}

	public void setEnabled(boolean enabled) {
		this.textField.setEditable(enabled);
	}

	public void requestFocus() {
		this.textField.requestFocus();
	}

	public JTextField getTextField() {
		return this.textField;
	}

	public boolean accept(Object value) {
		return (value instanceof String);
	}
}